/**
 * 网络请求封装
 */
import config from './config.js'
import util from './util.js'

// 获取接口地址
const _getPath = path => (config.baseUrl() + path)



// 封装接口公共参数
const _getParams = (data = {}) => {
  const timestamp = Date.now()
  const deviceId = Math.random()
  const version = data.version || config.version
  const appKey = data.appKey || config.appKey
  //加密下，防止其他人随意刷接口
  const sign = data.sign || util.md5(config.appKey + timestamp + deviceId)
  return Object.assign({}, {
    timestamp,
    sign,
    deviceId,
    version,
    appKey
  }, data)
}

// 修改接口默认content-type请求头
const _getHeader = (headers = {}) => {
  return Object.assign({
    'content-type': `application/x-www-form-urlencoded`
  }, headers)
}
// 存储登录态失效的跳转
const _handleCode = (res) => {
  const {
    statusCode
  } = res
  const {
    msg,
    code
  } = res.data
  // code为 4004 时一般表示storage里存储的token失效或者未登录
  if (statusCode === 200 && (code === 4004)) {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
  return true
}

/**
 * get 请求， post 请求
 * @param {String} path 请求url，必须
 * @param {Object} params 请求参数，可选
 * @param {String} method 请求方式 默认为 POST
 * @param {Object} option 可选配置，如设置请求头 { headers:{} }
 *
 * option = {
 *  headers: {} // 请求头
 * }
 *
 */

export const sendPost = (path, params) => {

  const url = _getPath(path)
  // const data = _getParams(params)
  const data = params
  /**
   * 这个框架，尽最大限度保证openid保存在了storage里边，除了codeLogin接口，
   * 其他接口都会默认携带openid参数，每个页面data里边不需要再保存openid，
   * openid默认就是当前用户自己的openid
   */
  if (!data.openid && path != config.codeLoginApi) {
    if (wx.getStorageSync('openid')) {
      data.openid = wx.getStorageSync('openid')
    } else {
      wx.showToast({
        title: '系统异常，请联系客服',
        icon:'none'
      })
      return
    }
  }
  // 处理请求头
  const header = util.extend(
    true, {
      "content-type": "application/x-www-form-urlencoded"
    },
    header
  );
  const method = 'POST'
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => {
        resolve(res.data)
      },
      fail: function (res) {
        reject(res.data)
      }
    });
  })
}

export const sendGet = (path, params) => {
  const url = _getPath(path)
  // const data = _getParams(params)
  const data = params
  // 处理请求头
  const header = util.extend(
    true, {
      "content-type": "application/x-www-form-urlencoded",
    },
    header
  );
  const method = 'GET'
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => {
        console.log(res.data)
        resolve(res.data)
      },
      fail: function (res) {
        reject(res.data)
      }
    });
  })
}

export const sendPut = (path, params) => {
  const url = _getPath(path)
  // const data = _getParams(params)
  const data = params
  // 处理请求头
  const header = util.extend(
    true, {
      "content-type": "application/x-www-form-urlencoded"
    },
    header
  );
  const method = 'PUT'
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => {
        console.log(res.data)
        resolve(res.data)
      },
      fail: function (res) {
        reject(res.data)
      }
    });
  })
}

export const sendDelete = (path, params) => {
  const url = _getPath(path)
  // const data = _getParams(params)
  const data = params
  // 处理请求头
  const header = util.extend(
    true, {
      "content-type": "application/x-www-form-urlencoded"
    },
    header
  );
  const method = 'DELETE'
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => {
        console.log(res.data)
        resolve(res.data)
      },
      fail: function (res) {
        reject(res.data)
      }
    });
  })
}

/**
 * 上传文件到后台
 * @param {*} path 接口地址
 * @param {*} filePath 临时文件的路径
 * @param {*} fileName 接收文件流的name
 * @param {*} params 传递的参数object
 */
export const uploadFile = (path, filePath, fileName, params) => {
  console.log(params)
  const url = _getPath(path)
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      header: {
        'content-type': 'multipart/form-data'
      },
      name: fileName,
      formData: params,
      success(res) {
        console.log(res)
        resolve(res)
      },
      fail(e) {
        console.log(e)
        reject(res)
      }
    })

  })
}